package com.example.back.controller;

import com.example.back.service.DeepSeekService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.io.IOException;
import java.io.PrintWriter;
import org.springframework.web.bind.annotation.CrossOrigin;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "http://localhost:5173", allowedHeaders = "*", methods = {
    RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT,
    RequestMethod.DELETE, RequestMethod.OPTIONS
})
public class ChatController {

    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);
    private final DeepSeekService deepSeekService;
    
    public ChatController(DeepSeekService deepSeekService) {
        this.deepSeekService = deepSeekService;
    }
    
    @PostMapping(value = "/chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public ResponseEntity<StreamingResponseBody> chat(@RequestBody Map<String, String> request) {
        logger.info("Received chat message");
        String message = request.get("message");
        if (message == null || message.isEmpty()) {
            return ResponseEntity.badRequest().body(outputStream -> {
                try (PrintWriter writer = new PrintWriter(outputStream)) {
                    writer.write("消息不能为空");
                }
            });
        }
        
        try {
            String prompt = "你是一个专业的程序员助手，请用专业且友好的语气回答问题。\n\n" + message;
            
            // 使用流式响应
            StreamingResponseBody responseBody = outputStream -> {
                try {
                    String response = deepSeekService.generateCode(prompt);
                    PrintWriter writer = new PrintWriter(outputStream);
                    
                    // 模拟流式输出，每个字符间隔一小段时间
                    for (char c : response.toCharArray()) {
                        writer.print(c);
                        writer.flush();
                        try {
                            // 添加小延迟以模拟流式效果
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                } catch (Exception e) {
                    logger.error("流式响应错误", e);
                    PrintWriter writer = new PrintWriter(outputStream);
                    writer.write("服务器错误: " + e.getMessage());
                    writer.flush();
                }
            };
            
            return ResponseEntity
                    .ok()
                    .contentType(MediaType.TEXT_EVENT_STREAM)
                    .body(responseBody);
                    
        } catch (Exception e) {
            logger.error("Chat error", e);
            return ResponseEntity.internalServerError().body(outputStream -> {
                try (PrintWriter writer = new PrintWriter(outputStream)) {
                    writer.write("服务器错误: " + e.getMessage());
                }
            });
        }
    }
} 